package com.laiyunocrapi.ocrapi.ocr.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.laiyunocrapi.ocrapi.ocr.common.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/aliyunOcr")
//@Api(value="OCR Service Controller", description = "阿里云OCR测试")
public class OCRController {

//    引入阿里云请求配置依赖
    @Value("${aliyunhost}")
    private String host;

    @Value("${aliyunpath}")
    private String path;

    @Value("${aliyunmethod}")
    private String method;

    @Value("${aliyunappcode}")
    private String appcode;

//    @ApiOperation(value = "OCR图片文字识别", notes = "OCR图片文字识别", httpMethod = "POST")
    @RequestMapping(value = "/discriminateOcrApi", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String,Object>> discriminateOcrApi(@RequestParam("images")MultipartFile[] multipartFiles) throws Exception {
        List<Map<String,Object>> resultDataList = new ArrayList<>();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        for (int i = 0; i<multipartFiles.length;i++){
            MultipartFile multipartFile = multipartFiles[i];
            byte[] imgData = multipartFile.getBytes();
            //转成Base64
            String imageBase64Code=new BASE64Encoder().encode(imgData);
            //新建一个map 用来存储返回的数据
            Map<String,Object> resultDataMap = new HashMap<>();
        /*
        {
          //图像数据：base64编码，要求base64编码后大小不超过4M，最短边至少15px，最长边最大4096px，支持jpg/png/bmp格式，和url参数只能同时存在一个
          "img": "",
          //图像url地址：图片完整URL，URL长度不超过1024字节，URL对应的图片base64编码后大小不超过4M，最短边至少15px，最长边最大4096px，支持jpg/png/bmp格式，和img参数只能同时存在一个
          "url": "",
          //是否需要识别结果中每一行的置信度，默认不需要。 true：需要 false：不需要
          "prob": false
        }
        */
//        String bodys =  "{\"img\":\""+ changeToBase64("D:\\f839c21d006298dcda515af16996053f.jpg")+"\",\"prob\":false}";
        String bodys =  "{\"img\":\""+ imageBase64Code+"\",\"prob\":false}";
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            System.out.println(response.toString());
            //获取response的body
            String prase = prase(EntityUtils.toString(response.getEntity()));
            resultDataMap.put("retWorld",prase);
            resultDataList.add(resultDataMap);
        } catch (Exception e) {
            e.printStackTrace();
         }
        }
        return resultDataList;
    }


    /**
     * 输出获取的Json返回值，并把它输出到控制台和文件
     * @param content 获取的Json返回值
     */
    public static void output(String content) {
        System.out.println(content);
        File file = new File("D:\\result.txt");  //这里选择输出文件的地址
        try {
            FileWriter writer = new FileWriter(file, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 解析Json
     * @param string 获取response中的Json
     */
    public static String prase(String string){
        JSONObject jsonObject= JSONObject.parseObject(string);
        JSONArray jsonArray=jsonObject.getJSONArray("prism_wordsInfo");
        //通过stringBuffer 获取识别的数据
        StringBuffer stringBuffer = new StringBuffer();
        for (int i=0;i<jsonArray.size();i++){
            JSONObject newjsonObject=(JSONObject) jsonArray.get(i);
           /*   输出到本地 暂时不需要 先注释
            output(newjsonObject.getString("word"));*/
            stringBuffer.append(newjsonObject.getString("word"));
        }
        //循环完毕，将StringBuffer转为String
        return stringBuffer.toString();
    }

    /**
     * 将文件读取并转化为Base64字符串
     * @param fileName 文件名
     * @return  Base64字符串
     * @throws Exception
     */
    public static String changeToBase64(String fileName) throws Exception{
        File file = new File(fileName);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int)file.length()];
        inputFile.read(buffer);
        inputFile.close();
        String base64Code=new BASE64Encoder().encode(buffer);
        return base64Code;
    }

}

